package hku.cs.lunuo;

import hku.cs.lunuo.cost.Expense;
import hku.cs.lunuo.rank.Model;
import hku.cs.lunuo.rank.Voter;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

public class CopyOfMain {
	public CopyOfMain(Global.Singleton s) {
	}

	public static CopyOfMain v() {
		return Global.v()._Main();
	}

	public static void main(String[] args) {
		try {

			File process_dir = null;
			File models = null;
			for (int i = 0; i < args.length; i++) {
				if (args[i].equals("-models"))
					models = new File(args[++i]);
				else if (args[i].equals("-process-dir"))
					process_dir = new File(args[++i]);
			}

			// Main.v().runTest(args);
			SAXBuilder sb = new SAXBuilder();
			Document xmlDoc = sb.build(models);
			Element xmlRoot = xmlDoc.getRootElement();
			Iterator xmlModelIt = xmlRoot.getChildren("model").iterator();
			while(xmlModelIt.hasNext()) {
				Element xmlModel = (Element)xmlModelIt.next();
				String klassName = xmlModel.getChildText("class");
				Class cl = Class.forName(klassName);
				Global.v().model = (Model)cl.newInstance();
				String voter = xmlModel.getChildText("voter");
				cl = Class.forName(voter);
				Global.v().voter = (Voter)cl.newInstance();
				
				CopyOfMain.v().runAnalyze(process_dir, null);
				Global.v().reset();
			}
			
			
		} catch (OutOfMemoryError e) {
			Global.v().out.println("Lunuo out of Memory");
			throw e;
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void runAnalyze(File data, List<String> args) {
		Model model = Global.v().model;
		model.prepaerProfile(data, args);
		model.analyze();
		model.toStmt();
		model.rank();
		new Expense().getExpense(Global.v().result);
	}

	private void runTest(String[] args) {
		int junit_version = 3;
		String output_dir = "";
		String test = "";
		for (int i = 0; i < args.length; i++) {
			if (args[i].equals("-junit-version"))
				junit_version = Integer.parseInt(args[++i]);
			else if (args[i].equals("-output-dir"))
				output_dir = args[++i];
			else
				test = args[i];
		}
		String[] as = new String[] { output_dir, test };
		if (junit_version == 3)
			Main3.main(as);
		else if (junit_version == 4)
			Main4.main(as);
	}

}
